﻿using Dynamics.NAV.Metro.Common;
using Okra.Data;
using System;
using System.Collections.Generic;
using System.Composition;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Dynamics.NAV.Metro.Data
{
    [Export(typeof(INavCustomerDataSource))]
    [Shared]
    public class NavCustomerDataSource : INavCustomerDataSource
    {
        private IList<NavCustomer> _customers;
        private NavCustomerDataListSource _dataListSource;
        private NavCompany _currCompany;

        public NavCustomerDataSource()
        {
            if (Windows.ApplicationModel.DesignMode.DesignModeEnabled)
            {
                _customers = (IList<NavCustomer>)new List<NavCustomer>();
                _customers.Add(new NavCustomer() { Index = 0, Name = "John", No = "1234", Email = "test@test.com" });
                _customers.Add(new NavCustomer() { Index = 1, Name = "Brian", No = "5678", Email = "test@test.com" });
                _customers.Add(new NavCustomer() { Index = 2, Name = "Jesper", No = "9837", Email = "test@test.com" });
                _customers.Add(new NavCustomer() { Index = 3, Name = "Kenneth", No = "893489", Email = "test@test.com" });
                _customers.Add(new NavCustomer() { Index = 4, Name = "Michael", No = "9984", Email = "test@test.com" });
            }
        }

        [Import]
        public IDynamicsNavApi NavApi { get; set; }

        public IList<NavCustomer> GetCustomers()
        {
            if (Windows.ApplicationModel.DesignMode.DesignModeEnabled)
                return _customers;

            if (NavApi == null)
                NavApi = new DynamicsNavApi();

            if (NavApi.CurrentCompany != _currCompany)
            {
                _currCompany = NavApi.CurrentCompany;
                _customers = null;
                _dataListSource = null;
            }

            if (_dataListSource == null)
                _dataListSource = new NavCustomerDataListSource();

            // Create a single instance of the customer list
            // This can then be shared between multiple view models
            if ((_dataListSource != null) && (_customers == null))
            {
                _customers = (IList<NavCustomer>)new VirtualizingDataList<NavCustomer>(_dataListSource);
            }

            return _customers;
        }
    }
}
